package com.yf.notify.jobs;

import com.yf.base.api.exception.ServiceException;
import com.yf.job.service.JobService;
import com.yf.notify.enums.MsgState;
import com.yf.notify.enums.MsgType;
import com.yf.notify.modules.email.factory.EmailFactory;
import com.yf.notify.modules.notify.entity.Msg;
import com.yf.notify.modules.notify.entity.MsgRead;
import com.yf.notify.modules.notify.entity.MsgTmpl;
import com.yf.notify.modules.notify.service.MsgPropService;
import com.yf.notify.modules.notify.service.MsgReadService;
import com.yf.notify.modules.notify.service.MsgService;
import com.yf.notify.modules.notify.service.MsgTmplService;
import com.yf.notify.modules.sms.factory.SmsFactory;
import lombok.extern.log4j.Log4j2;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 获取视频时长的任务
 * @author bool
 */
@Log4j2
@Component
public class MsgSendJob implements Job {

    @Autowired
    private MsgService msgService;

    @Autowired
    private MsgPropService msgPropService;

    @Autowired
    private MsgTmplService msgTmplService;

    @Autowired
    private MsgReadService msgReadService;

    @Autowired
    private SmsFactory smsFactory;

    @Autowired
    private EmailFactory emailFactory;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        JobDetail detail = jobExecutionContext.getJobDetail();
        String name = detail.getKey().getName();
        String group = detail.getKey().getGroup();
        String msgId = String.valueOf(detail.getJobDataMap().get(JobService.TASK_DATA));

        log.info("++++++++++定时任务：处理消息发送");
        log.info("++++++++++jobName:{}", name);
        log.info("++++++++++jobGroup:{}", group);
        log.info("++++++++++taskData:{}", msgId);

        // 查找消息
        Msg msg = msgService.getById(msgId);

        // 消息模板
        MsgTmpl tmpl = msgTmplService.getById(msg.getTmplId());

        // 接收人员
        List<MsgRead> readList = msgReadService.listByMsg(msgId);

        // 参数列表
        LinkedHashMap<String,String> params = msgPropService.findAll(msgId);

        // 开始发送
        msg.setSendState(MsgState.SENDING);
        msg.setResult("发送中..");
        msgService.updateById(msg);

        // 是否成功
        boolean success = false;
        String error = "";

        // 短信
        if(MsgType.SMS.equals(msg.getMsgType())){
            List<String> mobiles = new ArrayList<>();
            for(MsgRead read: readList){
                mobiles.add(read.getReceiver());
            }

            String [] arr = mobiles.toArray(new String[0]);
            try {
                success = smsFactory.getService().sendSms(tmpl.getSmsTmpl(), arr, params);
                mobiles.clear();
            }catch (ServiceException e){
                error = e.getMsg();
            }
        }

        // 邮件
        if(MsgType.EMAIL.equals(msg.getMsgType())){
            List<String> emails = new ArrayList<>();
            for(MsgRead read: readList){
                emails.add(read.getReceiver());
            }

            String [] arr = emails.toArray(new String[0]);
            try {
                success = emailFactory.getService().sendMail(msg.getTitle(), arr, msg.getContent(), tmpl.getEmailTmpl(), params);
                emails.clear();
            }catch (ServiceException e){
                error = e.getMsg();
            }
        }

        // 已发送
        msg.setSendState(success? MsgState.SENDED:MsgState.FAIL);
        msg.setResult(error);
        msg.setSendTime(new Date());
        msgService.updateById(msg);

    }



}